package com.example.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.gulimall.product.service.CategoryBrandRelationService;
import com.example.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimall.product.dao.CategoryDao;
import com.example.gulimall.product.entity.CategoryEntity;
import com.example.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> menus = categoryEntities.stream().filter(category -> category.getParentCid() == 0)
                .map(category -> {
                    category.setChildren(getChildren(category, categoryEntities));
                    return category;
                }).sorted((a, b) -> {
                    return (a.getSort() == null ? 0 : a.getSort()) - (b.getSort() == null ? 0 : b.getSort());
                }).collect(Collectors.toList());
        return menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前菜单是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCateLogPathById(Long catelogId) {
        LinkedList<Long> path = new LinkedList<>();
        findPath(catelogId,path);
        Collections.reverse(path);
        return path.toArray(new Long[path.size()]);
    }
    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Catagories() {
        List<CategoryEntity> categoryEntities = baseMapper
                .selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    @Override
    public Map<String, List<Catelog2Vo>> getCategoryMap() {
        return getCategoryMapFromDB();
    }


    public Map<String, List<Catelog2Vo>> getCategoryMapLock() {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String catalogJson = ops.get("catalogJson");
        if(StringUtils.isEmpty(catalogJson)) {
            synchronized (this) {
                if (StringUtils.isEmpty(catalogJson)) {
                    Map<String, List<Catelog2Vo>> categoryMapFromDB = getCategoryMapFromDB();
                    String s = JSON.toJSONString(categoryMapFromDB);
                    ops.set("catalogJson", s);
                    return categoryMapFromDB;
                } else {
                    return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
                    });
                }
            }
        }
        return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2Vo>>>(){});
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCategoryMapFromDB() {
        List<CategoryEntity> list = this.list();
        List<CategoryEntity> level1Catagories = getLevel1Catagories();
        Map<String, List<Catelog2Vo>> catelogMap=level1Catagories.stream().collect(Collectors.toMap(item->item.getCatId().toString()
                ,item->{
                    List<CategoryEntity> categoryEntities=getCategoryByParentCId(list,item.getCatId());
                    List<Catelog2Vo> category2Vos=null;
                    if(categoryEntities!=null){
                        category2Vos = categoryEntities.stream().map(entity -> {
                            List<CategoryEntity> category3 = getCategoryByParentCId(list, entity.getCatId());
                            List<Catelog2Vo.Category3Vo> category3Vos = category3.stream().map(e -> {
                                return new Catelog2Vo.Category3Vo(e.getParentCid().toString(), e.getCatId().toString(), e.getName());
                            }).collect(Collectors.toList());
                            Catelog2Vo catelog2Vo = new Catelog2Vo(entity.getParentCid().toString(), category3Vos,
                                    entity.getName(), entity.getCatId().toString());
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return category2Vos;
                }));
        return catelogMap;
    }

    @Override
    public void updatCascade(CategoryEntity category) {
        updateById(category);
        if(StringUtils.isNotEmpty(category.getName())){
            categoryBrandRelationService.updateCategory(category);
        }
    }

    private List<CategoryEntity> getCategoryByParentCId(List<CategoryEntity> list, Long catId) {
        List<CategoryEntity> collect = list.stream().filter(item -> {
            return item.getParentCid().equals(catId);
        }).collect(Collectors.toList());
        return collect;
    }

    private void findPath(Long catelogId,LinkedList<Long> path){
        if(catelogId!=0){
            path.add(catelogId);
            CategoryEntity child=getById(catelogId);
            findPath(child.getParentCid(),path);
        }
    }

    public List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> categoryEntities){
        List<CategoryEntity> childrens = categoryEntities.stream().filter(item -> item.getParentCid() == root.getCatId())
                .map(item -> {
                    item.setChildren(getChildren(item, categoryEntities));
                    return item;
                }).sorted((a, b) -> {
                    return (a.getSort() == null ? 0 : a.getSort()) - (b.getSort() == null ? 0 : b.getSort());
                }).collect(Collectors.toList());
        return childrens;
    }

}